import ApiFetchers from "@/apis/api_fetchers"
import { Repository } from "@/atoms/api_repositories"
import { tokenStore } from "@/utils/cached"
import { PATHS } from "@/constants/path"
import { createLogger } from "@/utils/logger"
import { toast } from "react-toastify"
import { useFavoriteGame, useUserWallet } from "./business/HomePage_deprecated/atoms_deprecated"
import { useUserInfo } from "./business/HomePage_deprecated"
export interface LoginResponse {
    accessToken: string
    accessTokenExp: number
    refreshToken: string
    refreshTokenExp: number
    token: string
}

const logger = createLogger("useAuth")

export function useAuth() {
    const { fetch: fetchUserInfo } = Repository.useUserInfo()
    const { clearUserInfo } = useUserInfo()
    const { clearUserWallet } = useUserWallet()
    const { clearFavorite } = useFavoriteGame()
    const sendVerifyCode = async (phoneNumber: string, countryCode = "63") => {
        try {
            const res = await ApiFetchers.sendOtpPhoneNumber({
                phoneNumber,
                countryCode: countryCode.replace("+", ""),
            })
            return {
                success: !!res,
                data: res,
            }
        } catch (error) {
            return {
                success: false,
                error,
            }
        }
    }
    const loginWithOtp = async (otpId: string, otpCode: string) => {
        try {
            await ApiFetchers.loginWithOtp({ otpId, otpCode })
            await fetchUserInfo()
            return {
                success: true,
            }
        } catch (error) {
            logger.debug("loginWithOtp error", error)
            return {
                success: false,
                error,
            }
        }
    }

    const loginWithPassword = async (countryCode: string, number: string, password: string) => {
        try {
            await ApiFetchers.loginWithPassword({
                countryCode,
                number,
                password,
            })
            await fetchUserInfo()
            return {
                success: true,
            }
        } catch (error) {
            return {
                success: false,
                error,
            }
        }
    }
    const logout = async () => {
        try {
            await ApiFetchers.logout()
            tokenStore.clear()
            clearUserInfo()
            clearUserWallet()
            clearFavorite()
            window.location.href = PATHS.INDEX
        } catch (error) {
            toast.error("Logout failed")
        }
    }

    return {
        fetchUserInfo,
        sendVerifyCode,
        loginWithPassword,
        loginWithOtp,
        logout,
    }
}
